<template>
  <div class="editinfo">
    <el-form
      :model="infoForm"
      :rules="infoRules"
      status-icon
      label-position="right"
      label-width="100px"
      style="max-width: 500px"
      ref="formRef"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="infoForm.name"/>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="infoForm.phone" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="infoForm.email" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="infoForm.gender">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
    </el-form>

    <div class="btn">
      <el-button type="primary" @click="handleUpdateClick">保存</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, watch, computed } from 'vue';
import { binMsg } from '@/global/api.js'
import { infoRules } from './rules/infoRules'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const store = useStore()

const userInfo = computed(() => store.state.userModule.userInfo)
const infoForm = reactive({
  id: userInfo.value.id,
  phone: userInfo.value.phone,
  email: userInfo.value.email,
  gender: userInfo.value.gender,
  name: userInfo.value.name
})
const formRef = ref(null)

// 点击保存按钮事件
const handleUpdateClick = async () => {
  binMsg().closeAll()
  await formRef.value.validate(async valid => {
    if (valid) {
      updateInfo()
    }
  })
}

// 发起请求修改信息
const updateInfo = async () => {
  try {
    await ElMessageBox.confirm('是否确认修改个人信息？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true
    })
    // 发起请求修改信息
    store.dispatch('userModule/updateInfoAction', { role: userInfo.value.role, infoForm })
  } catch (e) {
    binMsg('info', '已取消')
  }
}

// 重置
const reset = () => {
  // 对该表单项进行重置，将其值重置为初始值并移除校验结果
  formRef.value.resetFields()
  infoForm.gender = userInfo.value.gender
  infoForm.phone = userInfo.value.phone
  infoForm.email = userInfo.value.email
  infoForm.name = userInfo.value.name
}

// 监听路由的变化，如果离开了当前组件就重置表单项
watch(
  () => route.path,
  val => {
    if (!val.includes('/home/personal/info')) {
      reset()
    }
  }
)
</script>

<style lang="less" scoped>
.editinfo {
  .btn {
    padding: 10px 0 0 100px;
  }
}
.el-form-item {
  user-select: none;
}

.el-select {
  width: 500px;
  user-select: none;
}

/deep/ .el-input {
  font-weight: 700 !important;
  height: 100% !important;
}

/deep/ .el-form-item__label {
  font-weight: 700 !important;
}
</style>
